<template>
  <div style="width: 100%; height: 100%">
    <div class="titleImg" style="border-bottom: 4px solid lightgray">
      <el-carousel :interval="4000" type="card" height="200px">
        <el-carousel-item v-for="i in titleImg" :key="i">
          <img :src="i" alt="" srcset="" />
        </el-carousel-item>
      </el-carousel>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="美景" name="first"> </el-tab-pane>
      <el-tab-pane label="美食" name="second"> </el-tab-pane>
    </el-tabs>
    <div style="height: auto">
      <div class="search" style="display: flex; margin-left: 10px">
        <el-input
          v-model="search"
          placeholder="请输入搜索内容"
          style="width: 200px"
        ></el-input
        ><el-button
          icon="el-icon-search"
          circle
          style="margin-left: 20px"
          @click="searchData(search)"
        ></el-button>
        <el-button
          icon="el-icon-plus"
          circle
          style="margin-left: 20px; color: #9bc9d3"
          @click="addInfo = true"
          v-if="identity && userAudit == 'true'"
        ></el-button>
      </div>
      <div
        class="content"
        v-loading="tableData.length <= 0"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-row>
          <!-- tableData =  activeName=='first' ? this.tableDataCamera : this.tableDataFood -->
          <el-col
            :span="4"
            v-for="(item, index) in tableData"
            :key="index"
            style="padding: 5px"
          >
            <el-card :body-style="{ padding: '5px' }" shadow="hover">
              <img :src="item.shareImg" class="image" height="150px" />
              <div style="padding: 6px">
                <i class="el-icon-food" v-if="item.shareType == 'food'"></i>
                <i class="el-icon-camera" v-else></i>
                <span> {{ item.shareTitle }} </span>
                <el-tooltip
                  :disabled="disabled"
                  :content="item.shareDesc"
                  placement="bottom"
                  effect="light"
                >
                  <p
                    @click="disabled = !disabled"
                    style="
                      word-break: keep-all;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      font-size: 10px;
                      color: gray;
                      text-decoration: underline;
                      font-style: oblique;
                    "
                  >
                    {{ item.shareDesc }}
                  </p>
                </el-tooltip>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <!-- 信息添加弹框 -->
        <el-dialog
          title="添加信息"
          :visible.sync="addInfo"
          center
          @close="hidden"
        >
          <el-form :model="addform" ref="addForm" :rules="rules">
            <el-form-item label="分享图片" :label-width="formLabelWidth">
              <el-upload
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleChange"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :limit="1"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 图片预览 -->
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
              <!-- <img :src="addform.img" alt="" height="200px" width="200px" /> -->
            </el-form-item>
            <el-form-item label="分享属性" :label-width="formLabelWidth">
              <div>
                <el-radio v-model="addform.type" label="camera" border
                  >美景分享</el-radio
                >
                <el-radio v-model="addform.type" label="food" border
                  >美食分享</el-radio
                >
              </div>
            </el-form-item>
            <el-form-item
              label="分享Title"
              :label-width="formLabelWidth"
              required
              prop="title"
            >
              <el-input
                type="input"
                placeholder="给你分享的快乐"
                v-model="addform.title"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="这一缕风我想和你一起倾听ta的故事❤"
                v-model="addform.desc"
              >
              </el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addInfo = false">取 消</el-button>
            <el-button type="primary" @click="add('addForm', addform)"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
      <!-- //分页动态显示 -->
      <div class="pages">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[12]"
          :page-size="12"
          layout="total, prev, pager, next, jumper"
          :total="totalData"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      titleImg: [
       require('../assets/img/background.jpg'),
       require('../assets/img/topShare1.jpg'),
      require('../assets/img/topShare2.jpg'),
     require('../assets/img/topShare3.jpg'),
      ],
      disabled: false,
      activeName: "first",

      search: "",
      currentPage: 1,
      // nowData: this.formatDate(new Date()),
      totalData: 0,
      // 每页内容数据
      tableData: [],
      //总数据
      tableData1: [
        {
          img: "https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png",
          title: "分享名称",
          desc: "这一缕风我想和你一起倾听ta的故事❤",
          type: "food",
        },
      ],
      tableDataCamera: [],
      tableDataFood: [],
      // 详细信息弹框
      dialogFormVisible: false,
      form: {},
      formLabelWidth: "100px",
      // 添加信息
      addInfo: false,
      addform: {
        type: "food",
        // validDate: this.formatDate(new Date()),
      },
      // 图片
      dialogImageUrl: "",
      dialogVisible: false,
      // 图片列表
      fileList: [],
      rules: {
        title: [{ required: true, message: "请输入分享名称", trigger: "blur" }],
      },
      // 新tag
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      // 是否登录
      identity: "",
      userAudit:"",
    };
  },
  created() {
    this.getData();
    this.identity = window.sessionStorage.getItem("identity");
    this.userAudit = window.sessionStorage.getItem("userAudit");
  },
  mounted() {},
  methods: {
    // tab切换
    handleClick(tab, event) {
      // console.log(tab, event);
      this.search = "";
      this.getData();
    },
    // 获取所有数据
    getData() {
      var that = this;
      axios({
        methods: "GET",
        url: "http://127.0.0.1:3000/share/shareCamera",
      })
        .then((res) => {
          if (res.data.code == 200) {
            that.tableDataCamera = res.data.data;
          } else {
            console.log("error", res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      setTimeout(() => {
        axios({
          methods: "GET",
          url: "http://127.0.0.1:3000/share/shareFood",
        })
          .then((res) => {
            if (res.data.code == 200) {
              that.tableDataFood = res.data.data;
            } else {
              console.log("error", res);
            }
          })
          .catch((err) => {
            console.log(err);
          });
        if (this.activeName == "first") {
          that.tableData = that.tableDataCamera.slice(0, 12);
          that.totalData = that.tableDataCamera.length;
        } else {
          that.tableData = that.tableDataFood.slice(0, 12);
          that.totalData = that.tableDataFood.length;
        }
      }, 100);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      if (this.activeName == "first") {
        this.tableData = this.tableDataCamera.slice(
          (this.currentPage - 1) * 12,
          this.currentPage * 12
        );
      } else {
        this.tableData = this.tableDataFood.slice(
          (this.currentPage - 1) * 12,
          this.currentPage * 12
        );
      }
    },
    // add
    // 图片
    handleChange(file, fileList) {
      console.log(file, fileList);
      for (let i = 0; i < fileList.length; i++) {
        fetch(fileList[i].url)
          .then((data) => {
            const blob = data.blob();
            console.log(blob);
            return blob;
          })
          .then((blob) => {
            let reader = new window.FileReader();
            reader.onloadend = function () {
              const data = reader.result;
              fileList[i].url = data;
            };
            reader.readAsDataURL(blob);
          });
      }
      var img = [];
      setTimeout(() => {
        for (let index = 0; index < fileList.length; index++) {
          img.push(fileList[index].url);
        }
        console.log(img);
      }, 300);

      this.fileList = img;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    queryTitleSearch(queryString, cb) {
      var restaurants = this.loadAllTitle;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    queryPlaceSearch(queryString, cb) {
      var restaurants = this.loadAllPlace;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    hidden() {
      //处理close
      this.addInfo = false;
      (this.addform = {
        type: "camera",
        // validDate: this.formatDate(new Date()),
      }),
        (this.dynamicTags = []);
      this.inputValue = "";
    },
    add(formName, item) {
      console.log(item);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log("submit!");
          item.img = this.fileList;
          axios
            .post("http://127.0.0.1:3000/share/addShare", {
              shareDesc: item.desc,
              shareImg: item.img[0],
              shareTitle: item.title,
              shareType: item.type,
              InfoPublisher: window.sessionStorage.getItem("userName"),
            })
            .then((data) => {
              if (data.data.code == 200) {
                window.location.reload();
              } else {
                this.$message.error("添加失败，请再次尝试");
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("图片过大，请再次尝试");
            });
          this.addInfo = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 新tag
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    addTag(value) {
      console.log(value);
      let inputValue = value;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 搜索
    searchData(data) {
      var that = this;
      var path = "";
      if (this.activeName == "first") {
        path = "searchCamera";
      } else {
        path = "searchfood";
      }
      if (data.length != 0) {
        console.log(path, "path");
        axios({
          methods: "GET",
          url: "http://127.0.0.1:3000/share/" + path,
          params: {
            searchTitle: data,
          },
        })
          .then((res) => {
            console.log("success", res);
            console.log(res.data.data);
            if (path == "searchCamera") {
              // that.tableData1 = res.data.data;
              that.tableDataCamera = res.data.data;
            } else {
              // that.tableData1 = res.data.data;
              that.tableDataFood = res.data.data;
            }
          })
          .catch((err) => {
            console.log(err);
          });
        setTimeout(() => {
          if (path == "searchCamera") {
            this.tableData = this.tableDataCamera.slice(0, 12);
            this.totalData = this.tableDataCamera.length;
          } else {
            this.tableData = this.tableDataFood.slice(0, 12);
            this.totalData = this.tableDataFood.length;
          }
        }, 200);
      } else {
        that.getData();
      }
    },
  },
};
</script>

<style scoped lang="css">
.el-card {
  height: auto !important;
}
.titleImg {
  height: 225px;
  width: 100%;
}
.titleImg img {
  height: 190px;
  margin: 5px auto;
  overflow: hidden;
}
img {
  height: 160px;
  width: 834px;
  margin: 5px auto;
  overflow: hidden;
}
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
.desc {
  overflow-y: hidden;
  height: 45px;
  font-size: 13px;
  color: #999;
  width: 100%;
  border: none;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  resize: none;
}
.time {
  display: block;
  padding-top: 8px;
  font-size: 13px;
  color: #999;
}
.bottom {
  margin-top: 8px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
.tags {
  margin-top: 8px;
}
.tags .el-tag {
  margin: 3px;
}
.el-card {
  height: 370px;
}
.pages {
  position: fixed;
  bottom: 10px;
  right: 10px;
}
/* 新tag */
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
/* 举报样式 */
.el-message-box__title {
  color: red !important;
  font-size: 9px !important;
}
</style>
